//引入用户构造函数
const {
    User
} = require('../../model/users')
require('../../util/ustil')
module.exports = async (req, res, next) => {
    //获取客户端传递过来的用户id和密码
    let {
        userId,
        password,
        orderTotal,
    } = req.body

    let addressList = req.body
    // console.log(addressList)

    //根据用户id查询数据
    const user = await User.findOne({
        userId
    })
    if (user) {
        //查询成功
        // 比对密码
        // console.log(user.password)
        if (user.password === password) {
            let goodList = user.cartList.filter(item => item.checked == '1')
            //定义订单对象
            let order = {}
            order.addressInfo = addressList
            order.orderTotal = orderTotal
            order.goodList = goodList
            order.orderStatus = '1'
            order.createTime = new Date().Format('yyyy-MM-dd hh:mm:ss')
            //订单编号
            const platform = '622'
            let r1 = Math.floor(Math.random() * 10)
            let r2 = Math.floor(Math.random() * 10)
            let sysDate = new Date().Format('yyyyMMddhhmmss')
            order.orderId = platform + r1 + sysDate + r2
            //插入数据
            user.orderList.push(order)
            //把cartList中checked为1的商品删掉
            user.cartList = user.cartList.filter(item => item.checked == '0')
            user.save()
            res.json({
                status: 200,
                msg: '支付成功,订单已生成',
                data: {
                    orderId: order.orderId,
                    orderTotal: order.orderTotal
                }
            })
        } else {
            res.json({
                status: 400,
                msg: '密码有误，支付失败!!!',
                data: ''
            })
        }
    } else {
        //查询用户失败
        res.json({
            status: 400,
            msg: '支付失败，请确认登陆状态!',
            data: ''
        })
    }
}